package com.cfets.annualAssessment.Servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * Created by ShenYiChou on 2017/7/25.
 */
@WebServlet(urlPatterns = { "/admin/verifyCode/restful" })
public class LoginFormServlet extends HttpServlet{
    private static final long serialVersionUID = 1L;

    public void init() throws ServletException {
        super.init();

    }


    public void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 生成服务器相应的service方法

        // 阻止生成的页面内容被缓存，保证每次重新生成随机验证码#####################

        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        // 指定图形验证码图片的大小；
        int width = 100;// 宽度
        int height = 30;// 高度
        int len = 4;//字符总数
        int fontHeight =  height;  //字体高度  height - 10 集中显示验证码
        int codeX = (width-4) / (len+1); //width-4 除去左右多余的位置，使验证码更加集中显示，减得越多越集中。  第一个字符的x轴值，因为后面的字符坐标依次递增，所以它们的x轴值是codeX的倍数
        int codeY = height - 7;   //codeY ,验证字符的y轴值，因为并行所以值一样
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 准备在图片中绘制内容
        // g.setColor,3次为了设置背景色
        Graphics2D g = image.createGraphics();
        Random random = new Random();
        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(0, 0, width, height);
        // 设置图形验证码中的字符串的字体的大小
        Font mFont = new Font("Times New Roman",Font.PLAIN,fontHeight);
        g.setFont(mFont);
        g.setColor(Color.LIGHT_GRAY);
        g.drawRect(0, 0, width - 1, height - 1);
        // 生成随机线条
	/*	for (int i = 0; i < 155; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}*/

        String sRand = generateRandString(len);
        char[] carr = sRand.toCharArray();
        // 生成随机的字符串并加入到图片中
        for (int i = 0; i < len; i++) {
            g.setColor(new Color(20 + random.nextInt(110), 20 + random
                    .nextInt(110), 20 + random.nextInt(110)));
            g.drawString(String.valueOf(carr[i]), (i + 1) * codeX, codeY);
        }
		HttpSession session = request.getSession(true);
		session.setAttribute("validate_code", sRand.toLowerCase());    //验证码放入session

		/*UserSession userSession = UserSessionHolder.get();
		System.out.println("*********************getUserSession:"+CheckUtil.isEmpty(userSession)+"****************");
		userSession.setValidateCode(sRand.toLowerCase());
		System.out.println("*******************setValidateCode:"+userSession.getValidateCode()+"**********************");
		//UserSessionHolder.put(userSession);
		System.out.println("*******************putUserSession**********************");*/
//        CookieUtil.addCookie(response, "validate_code", sRand.toLowerCase());			//验证码放入cookie
        g.dispose();
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }

    private String generateRandString(int len) {
        StringBuilder sRand = new StringBuilder();
        String tmp = null;
        while (sRand.length() < len) {
            tmp = getRandomChar().toLowerCase();
            if (!tmp.equals("0") && !tmp.equals("o") && !tmp.equals("1")
                    && !tmp.equals("i") && !tmp.equals("l")) {
                sRand.append(tmp);
            }
        }
        return sRand.toString();

    }

    // 随机生成字符串
    public static String getRandomChar() {
        int rand = (int) Math.round(Math.random() * 2);
        long itmp = 0;
        char ctmp = '\u0000';
        switch (rand) {
            case 1:
                itmp = Math.round(Math.random() * 25 + 65);
                ctmp = (char) itmp;
                return String.valueOf(ctmp);
            case 2:
                itmp = Math.round(Math.random() * 25 + 97);
                ctmp = (char) itmp;
                return String.valueOf(ctmp);
            default:
                itmp = Math.round(Math.random() * 9);
                return String.valueOf(itmp);
        }
    }
}
